#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
编译选项配置
设置编译模式、详细输出等选项
"""

import os
import sys
import logging
import importlib.util
from SCons.Script import *

# 配置logging
logging.basicConfig(level=logging.INFO, format='%(message)s')

def generate(env):
    """
    配置编译环境和选项
    """
    # 基础编译环境配置
    # 确保使用C++编译器和标准库
    env['CXX'] = 'g++'
    env['CC'] = 'gcc'
    env.Replace(
        CPPPATH=[],
        LIBPATH=[],
        LIBS=['stdc++'],
        CCFLAGS=['-Wall', '-g'],
        CXXFLAGS=['-std=c++17']
    )
    env.Append(LINKFLAGS=['-Wl,--copy-dt-needed-entries'])
    
    # 加载自定义编译器选项（如果指定了CUST_OPTION环境变量）
    _load_custom_options(env)
    
    # 添加编译器选项
    AddOption('--target',
              dest='target',
              type='string',
              nargs=1,
              action='store',
              metavar='TARGET',
              help='指定要编译的目标模块')
    
    AddOption('--release',
              dest='release',
              action='store_true',
              help='发布版本编译')
    
    AddOption('--verbose',
              dest='verbose',
              action='store_true',
              help='详细输出编译信息')
    
    # 打印构建系统信息阶段
    logging.info("╔═════════════════════════════════════════════════════════════════════════╗")
    logging.info("║                     Phase1 -- Build system information                  ║")
    logging.info("╚═════════════════════════════════════════════════════════════════════════╝")
    
    # 设置编译模式
    if GetOption('release'):
        env.Append(CCFLAGS=['-O2', '-DNDEBUG'])
        env.Append(CXXFLAGS=['-O2', '-DNDEBUG'])
        logging.info("Build mode: Release")
    else:
        env.Append(CCFLAGS=['-O0', '-DDEBUG'])
        env.Append(CXXFLAGS=['-O0', '-DDEBUG'])
        logging.info("Build mode: Debug")
    
    # 设置详细输出
    if GetOption('verbose'):
        env['VERBOSE'] = True
        logging.info("Verbose output: Enabled")
    else:
        # 简化编译输出，只显示正在编译的文件
        def print_cmd_line(s, target, source, env):
            """自定义编译输出格式"""
            # 获取源文件和目标文件
            if source and target:
                src_file = str(source[0]) if source else "未知源文件"
                tgt_file = str(target[0]) if target else "未知目标文件"
                
                # 判断操作类型
                if '.o' in tgt_file or '.os' in tgt_file:
                    # 编译操作
                    logging.info(f"===compile=== {src_file}")
                elif '.so' in tgt_file or '.a' in tgt_file or (not '.o' in tgt_file and not 'Copy' in str(s)):
                    # 链接操作（动态库、静态库或可执行文件）
                    logging.info(f"===link=== {tgt_file}")
                elif 'Copy' in str(s):
                    # 拷贝操作
                    logging.info(f"===copy=== {tgt_file}")
                else:
                    # 其他操作
                    logging.info(f"===build=== {tgt_file}")
            else:
                # 其他操作
                logging.info(f"===execute=== {str(s)[:60]}..." if len(str(s)) > 60 else f"===execute=== {s}")
        
        # 设置自定义输出格式
        env['PRINT_CMD_LINE_FUNC'] = print_cmd_line
    

    
    # 添加平台特定配置
    import platform
    system = platform.system().lower()

    logging.info(f"Target platform: {system}")
    
    return env

def _load_custom_options(env):
    """
    加载自定义编译器选项脚本
    如果设置了CUST_OPTION环境变量，则从指定的脚本中加载编译器相关参数
    这些参数将优先于默认的option.py设置生效
    """
    custom_option_path = os.environ.get('CUST_OPTION')
    if not custom_option_path:
        return
    
    if not os.path.exists(custom_option_path):
        logging.warning(f"Custom option script not found: {custom_option_path}")
        return
    
    try:
        # 使用SCons工具加载方式
        custom_tool_dir = os.path.dirname(custom_option_path)
        custom_tool_name = os.path.splitext(os.path.basename(custom_option_path))[0]
        
        logging.info(f"Loading custom options from: {custom_option_path}")
        env.Tool(custom_tool_name, toolpath=[custom_tool_dir])
        logging.info("Custom options loaded successfully")
            
    except Exception as e:
        logging.error(f"Failed to load custom options from {custom_option_path}: {e}")

def exists(env):
    """
    检查工具是否可用
    """
    return True